package com.ruoyi.common.config;

import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.AutoUpdateCertificatesVerifier;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.ByteArrayInputStream;
import java.security.PrivateKey;

/**
 * @title: WechartPayHttp
 * @copyright: copyright (c) 2023
 * @author: jiangguanjun
 * @date: 2023/10/20 15:21
 * @firstReview:
 * @lastReview:
 * @desc:
 */
@Component
public class WechartPayHttp {
    // 商户API私钥
    private static PrivateKey merchantPrivateKey;
    static {
        try {
            ResourceLoader resourceLoader = new DefaultResourceLoader();
           // Resource resource = resourceLoader.getResource("classpath:key.txt");
            merchantPrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream("MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQC4CrFzK7xpnTNNbDJkQtTDVJFRZtMMGCw1Qw3hld27H+p4PXpvSUGrerpWmv/GMzIFibC18SfBilJ+YM5ZU/zS4c92sPCOqLacnkZzBhREs6L51GVnMsAHef4WlT+EBBKPZYHuxy2Gb8QslDiOTVCPSjALIDqdAHejksNqCnpeYSHz8FaeaZMvto0c7pOBtXSuw8P/45xai5e6GNiyCoVBaSGTGadOKq3+P6a6qVb2hNq67aAlko+NaijRtPytIfvpB50m4NHSSOt1LzFaUqR/ZllsGQlyD6gpNkZoPw2KytvSwEJ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Ls/SQsFBqgbb4K54KlMewKBgQDaxmH3RjJEkG2OGEvNRUPAOJpbdxJS4+jqhlLkuJStMM1Q0tXLE4ziAPbfwLhLZpMA0McXMjAuGIQGCCsAQIBBNBkPn4bgJZh9RkEaR3s4ci/2Qu5Xz4nV1d1FqKIfY1oFQeYe90vnOag1RfLdDHJWbgb0r5wG80pdAHoep80Crw==".getBytes()));
          //  merchantPrivateKey = PemUtil.loadPrivateKey(resource.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Bean
    public PrivateKey privateKey() {
        return merchantPrivateKey;
    }

    /**
     * 商户号
     */
    @Value("${weixinpay.merchanid}")
    private String merchantId ;

    /**
     *  商户api证书的证书序列号
     */
    @Value("${weixinpay.mch-serial-no}")
    private String merchantSerialNumber;

    /**
     * 商户APIv3密钥
     */
    @Value("${weixinpay.api-v3-key}")
    private String apiV3key  ;

    @Bean("wxPayHttpClient")
    public CloseableHttpClient wxPayHttpClient(AutoUpdateCertificatesVerifier autoUpdateCertificatesVerifier) {
        return WechatPayHttpClientBuilder.create()
                .withMerchant(merchantId, merchantSerialNumber, merchantPrivateKey)
                .withValidator(new WechatPay2Validator(autoUpdateCertificatesVerifier))
                .build();
    }

    @Bean
    public AutoUpdateCertificatesVerifier autoUpdateCertificatesVerifier() {
        // 自动更新微信支付平台证书
        return new AutoUpdateCertificatesVerifier(
                new WechatPay2Credentials(merchantId, new PrivateKeySigner(merchantSerialNumber, merchantPrivateKey)),
                apiV3key.getBytes());
    }

    // 请求微信支付相关接口可以直接使用 wxPayRestTemplate
    @Bean("wxPayRestTemplate")
    public RestTemplate wxPayRestTemplate() {
        return new RestTemplate(new HttpComponentsClientHttpRequestFactory(wxPayHttpClient(autoUpdateCertificatesVerifier())));
    }
}
